<template>
  <div>
    <div class="remarkAndgrade">
      <div class="remarkBox">
        <el-input
          type="textarea"
          :autosize="{ minRows: 2, maxRows: 2 }"
          placeholder="评语："
          v-model="textarea"
        >
        </el-input>
        <div class="defaultRemark">
          <div
            class="reamrkDesc"
            v-for="(ritem, rindex) in defaultRemark"
            :key="rindex"
            @click="handelRemark(ritem)"
          >
            {{ ritem.title }}
          </div>
          <el-popover placement="top-end" width="326" v-model="visible">
            <div class="remarkList" :ref="'remark-Popover-' + taskStudentIndex">
              <div
                v-for="(rLitem, rlIndex) in moreRemark"
                :key="rlIndex"
                class="reamrkItem"
                :title="rLitem.title"
                @click="handelRemark(rLitem)"
              >
                {{ rLitem.title }}
              </div>
            </div>
            <div slot="reference" class="reamrkDesc otherRemarkIcon">
              <img :src="require('@/assets/images/down.png')" />
            </div>
          </el-popover>
        </div>
      </div>
      <div class="gradeBox">
        <div class="percentageScoreBox">
          <div class="inputBox">
            评分：
            <el-form
              :model="numberValidateForm"
              ref="numberValidateForm"
              label-width="100px"
              class="demo-ruleForm"
            >
              <el-form-item
                prop="score"
                :rules="[
                  { required: true, message: '不能为空' },
                  { type: 'number', message: '必须为数字值' },
                ]"
              >
                <el-input
                  maxlength="3"
                  type="score"
                  v-model.number="numberValidateForm.score"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
            </el-form>
          </div>
          <div class="scoreBtnBox">
            <div
              class="scoreBox"
              v-for="(sitem, sindex) in defaultScore"
              :key="sindex"
              @click="handelScore(sitem)"
            >
              {{ sitem }}
            </div>
          </div>
        </div>
        <div class="gradeBtn">
          <el-button
            :class="{
              commentDisabled:
                !numberValidateForm.score < 0 ||
                Number(numberValidateForm.score) < 0 ||
                textarea == '' ||
                this.sitem.taskState !== '已学',
              commented: checkCommentState,
            }"
            @click="handelCorrect"
            :loading="correcting"
            :disabled="
              !numberValidateForm.score < 0 ||
              Number(numberValidateForm.score) < 0 ||
              textarea == '' ||
              correcting ||
              this.sitem.taskState !== '已学'
            "
            :title="
              !numberValidateForm.score < 0 ||
              Number(numberValidateForm.score) < 0 ||
              textarea == ''
                ? '请填写评语及分数'
                : '完成批阅'
            "
          >
            {{
              this.sitem.taskState !== "已学"
                ? "未学完此任务"
                : checkCommentState
                ? "已批阅"
                : "完成批阅"
            }}
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { teacherComment } from "@/request/teacher";
import { location } from "@/util/tool";
import { mapState } from "vuex";
import { parse } from "qs";
export default {
  data() {
    return {
      textarea: "",
      defaultRemark: [
        { title: "你回答得真棒！再接再厉，加油！" },
        {
          title: "不错！",
        },
        {
          title: "态度决定高度，值得表扬",
        },
        {
          title: "方法还不够熟练哦，加把劲！",
        },
        {
          title: "要努力哦，争取做到更好！",
        },
      ],
      moreRemark: [
        {
          title: "再细心些，会更好啊！",
        },
        {
          title: "你近期表现棒极了！",
        },
        {
          title: "看你的作业是一种享受！",
        },
      ],
      defaultScore: [50, 60, 70, 80, 90],
      visible: false,
      numberValidateForm: {
        score: "",
      },
      correcting: false, // 批改中
    };
  },
  props: {
    taskStudentIndex: String,
    fitem: Object,
    sitem: Object, // 引导文学习数据
    titem: Object, // 当前任务学习数据
    taskGroupID: Number, // 任务组ID
    taskID: Number, // 任务ID
    studenData: Array, // 学生数据
  },
  watch: {
    "numberValidateForm.score"(n, o) {
      if (n > 100) {
        this.numberValidateForm.score = 100;
      }
    },
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo,
    }),
    checkCommentState() {
      // 这里的时间比较只适用于普通引导文，不适合刷题
      if (
        this.sitem.guidelineComment ||
        this.sitem.commentTime > this.sitem.lastUpdatedTime
      ) {
        return true;
      } else {
        return false;
      }
    },
  },
  created() {
    this.$nextTick(() => {
      let dropdownMenu = this.$refs["remark-Popover-" + this.taskStudentIndex];
      // dropdownMenu.setAttribute('remark-Popover')
      dropdownMenu.parentNode.classList.add("remark-Popover");
    });
    this.numberValidateForm.score = this.sitem.guidelineScore;
    this.textarea = this.sitem.guidelineComment;
  },
  methods: {
    // 点击点评内容
    handelRemark(item) {
      this.textarea = item.title;
      this.visible = false;
    },
    // 点击默认分数
    handelScore(value) {
      this.numberValidateForm.score = value;
    },
    // 完成批阅
    handelCorrect() {
      // let findCurrStudent = this.studenData.filter(
      //   (item) => item.userID === this.sitem.userID
      // )[0];
      // let findTaskGroup = findCurrStudent.taskCommitJson.filter(
      //   (item) => item.taskGroupID === this.taskGroupID
      // )[0];
      // let findTask = findTaskGroup.tasks.filter(
      //   (item) => item.taskID === this.taskID
      // )[0];
      this.correcting = true;
      const currTime = new Date().getTime();
      // 提交的数据模型
      const params = {
        chooseNo: Number(this.sitem.chooseNo), // 用户该课程的选课编号
        commentTime: currTime,
        commentUserID: this.userInfo.userID, // 当前评阅用户的ID
        currNo: Number(this.$route.query.currNo),
        state: "已学",
        taskGroupID: this.taskGroupID,
        taskID: this.taskID,
        userID: this.sitem.userID,
        taskScore: 99,
        guidelineResults: {},
      };
      params.guidelineResults[`${Number(this.sitem.guidelineID)}`] =
        Object.assign({}, this.sitem, {
          submitContent: JSON.parse(JSON.stringify(this.sitem.submitContent)),
          gameOrExciseRank: 0,
          gameOrExciseScore: 0,
          commentTime: currTime,
          commentUserID: this.userInfo.userID,
          guidelineScore: this.numberValidateForm.score,
          guidelineComment: this.textarea,
        });
      // 删除文件类型
      if (
        Array.isArray(
          params.guidelineResults[`${Number(this.sitem.guidelineID)}`]
            .submitContent?.data?.filePaths
        )
      ) {
        params.guidelineResults[
          `${Number(this.sitem.guidelineID)}`
        ].submitContent.data.filePaths.forEach((ditem) => {
          let baseFileUrl =
            params.guidelineResults[`${Number(this.sitem.guidelineID)}`]
              .submitContent.data.baseFileUrl;
          if (ditem.type) delete ditem.type;
          this.removeFileType(ditem, baseFileUrl);
        });
      }
      delete params.guidelineResults[`${Number(this.sitem.guidelineID)}`]
        .fState;
      // delete params.guidelineResults[`${Number(this.sitem.guidelineID)}`]
      //   .taskState;

      // Object.assign(
      //   this.sitem,
      //   params.guidelineResults[`${Number(this.sitem.guidelineID)}`]
      // );
      // Object.assign(findTask.guidelineResults, params.guidelineResults);
      // params.guidelineResults = findTask.guidelineResults;
      // debugger
      this.$parent.changeUserData(
        this.sitem,
        params.guidelineResults[`${Number(this.sitem.guidelineID)}`]
      );
      setTimeout(() => {
        teacherComment(params).then((res) => {
          this.correcting = false;
          if (res.errno === 0) {
            this.$antdMessage.success({
              content: "评阅成功！",
            });
            // 标注当前学生的引导文数据状态为已批阅  todo update
            let correctStudenData =
              this.$parent.$parent.$parent.$parent.$parent.$parent.studenData;
            let fuIndex = correctStudenData.findIndex(
              (item) => item.userID == this.sitem.userID
            );
            let fgIndex = correctStudenData[fuIndex]?.taskCommitJson.findIndex(
              (item) => item.taskGroupID == this.taskGroupID
            );
            let findGuideline =
              correctStudenData[fuIndex]?.taskCommitJson[fgIndex]?.taskResults[
                this.taskID
              ].guidelineResults[this.sitem.guidelineID];
            this.$set(findGuideline, "isComment", true);
          } else {
            this.$antdMessage.error({
              content: res.message || res,
            });
          }
        });
      }, 300);
    },
    // 删除文件类型
    removeFileType(data, baseFileUrl) {
      if (data.type) delete data.type;
      let exp = new RegExp(baseFileUrl + "/", "g");
      let httpExp = new RegExp(location(window), "g");
      let arr = [];
      data.fileUrl = data.fileUrl.replace(httpExp, "").replace(exp, "");
      if (data.subFiles && data.subFiles.length) {
        data.subFiles?.forEach((item) => {
          if (item.type) delete item.type;
          if (item.subFiles) {
            arr.push(this.removeFileType(item, item.fileUrl));
          } else {
            arr.push(item);
          }
          item.fileUrl = item.fileUrl
            .replace(httpExp, "")
            .replace(baseFileUrl + "/", "");
        });
      } else {
        return data;
      }
    },
  },
};
</script>

<style lang="stylus">
.remarkAndgrade {
  margin-top: 15px;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;

  .remarkBox {
    max-width: 470px;

    .el-textarea {
      .el-textarea__inner {
        resize: none;
        padding: 8px 10px;
        width: 435px;
        border-radius: 5px;
        border-color: #9fa7b6;
        font-family: PMingLiU-ExtB;
        font-size: 14px;
        line-height: 20px;
        color: #333333;
      }

      .el-textarea__inner::-webkit-scrollbar {
        width: 4px;
        // height: 1px;
      }

      .el-textarea__inner::-webkit-scrollbar-thumb {
        border-radius: 4px;
        -webkit-box-shadow: inset 0 0 1px #bfc4c3;
        background: #dbdbdb;
      }

      /* 定义滚动条所在轨道的样式。有圆角和阴影以及淡色系的背景色 */
      .el-textarea__inner::-webkit-scrollbar-track {
        -webkit-box-shadow: inset 0 0 1px #E6FAF3;
        border-radius: 4px;
      }

      .el-textarea__inner:focus {
        border-color: #9fa7b6;
      }
    }
  }

  .defaultRemark {
    display: flex;
    flex-flow: wrap row;

    .reamrkDesc {
      cursor: pointer;
      margin-right: 7px;
      padding: 3px 5px;
      margin-top: 10px;
      background: #fff;
      border-radius: 5px;
      border: solid 1px #9fa7b6;
      font-family: PMingLiU-ExtB;
      font-size: 14px;
      color: #999999;
    }

    .otherRemarkIcon {
      border: 0;
      transform: rotate(180deg);

      img {
        width: 22px;
        height: 11px;
      }
    }

    .reamrkDesc:hover {
      background: #fff6e1;
    }
  }

  .gradeBox {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    flex: 1;
    height: 100%;

    .percentageScoreBox {
      flex: 1;

      .inputBox {
        display: flex;
        align-items: center;
        justify-content: flex-end;

        .el-form {
          .el-form-item {
            margin: 0;

            .el-form-item__content {
              line-height: 1 !important;
              margin: 0 !important;

              .el-input {
                width: 48px;
                overflow: hidden;

                .el-input__inner {
                  padding: 0;
                  height: unset;
                  line-height: 22px;
                  border: none;
                  border-radius: 0;
                  text-align: center;
                  border-bottom: 1px solid #333333;
                  font-family: PMingLiU-ExtB;
                  font-size: 16px;
                  color: #f1ae3d;
                }
              }
            }
          }
        }
      }

      .scoreBtnBox {
        margin-top: 23px;
        display: flex;
        justify-content: flex-end;
        line-height: 1;

        .scoreBox {
          cursor: pointer;
          margin-left: 4px;
          padding: 0 10px;
          background-color: #ffffff;
          border-radius: 5px;
          border: solid 1px #9fa7b6;
          font-family: PMingLiU-ExtB;
          font-size: 14px;
          color: #999999;
        }

        .scoreBox:hover {
          background: #fff6e1;
        }
      }
    }

    .gradeBtn {
      margin-top: 35px;
      line-height: 1;

      button {
        cursor: pointer;
        float: right;
        outline: none;
        border: none;
        width: 130px;
        height: 50px;
        background-color: #f1ae3d;
        border-radius: 10px;
        font-family: PMingLiU-ExtB;
        font-size: 16px;
        color: #ffffff;
      }

      .commentDisabled {
        cursor: not-allowed;
        background: #7a7a7a;
      }

      .commented {
        background: #5ad551;
      }
    }
  }
}

.remark-Popover {
  padding: 12px 0;
  border-radius: 10px;
  border: solid 1px #707070;

  .remarkList {
    padding: 0 11px 0 21px;
    display: flex;
    flex-flow: column;

    .reamrkItem {
      cursor: pointer;
      padding: 7px;
      font-family: PMingLiU-ExtB;
      font-size: 14px;
      color: #999999;
      text-overflow: ellipsis;
      white-space: nowrap;
      overflow: hidden;
    }

    .reamrkItem:hover {
      background: #fff6e1;
    }
  }
}
</style>